/**
 * Created by MD-3 on 2017/8/7.
 */

function openDeviceInfo(deviceid, alarmCheck) {
//alarmCheck：用于默认显示报警标签页

    $.ajax({
        type : "POST",
        url : "infodata.json",
        data : {id : deviceid},
        dataType: 'json',
        success : function(data) {
            if( 1 != data.action){
                return;
            }
            var device = getDevById(deviceid);
            var id     = device.id;
            var type   = device.type;
            var name   = device.name;
            var marker = device.marker;
            var thead  = ['基本信息', '报警显示', '设备配置', '设备状态'];

            var title = createInfoTitle(name);
            var content = '';

            var alarmActive = '', basicActive = '';
            if (alarmCheck) {
                basicActive = ' class="tab-pane fade"';
                alarmActive = ' class="tab-pane fade in active"';
            } else {
                basicActive = ' class="tab-pane fade in active"';
                alarmActive = ' class="tab-pane fade"';
            }

            content = '<div class="my-infobody">'
                + createTabStr(thead, alarmCheck)

                + '<div id="myTabContent" class="tab-content">'
                    + '<div ' + basicActive + ' id="mybasic-info">'
                    + '    <table class="table table-hover">'
                    + '        <tbody>' + createBasicInfo(data.basicInfo) + '</tbody>'
                    + '    </table>'
                    + '</div>'

                    + '<div ' + alarmActive + ' id="myalarm-info">'
                    + '    <table class="table table-hover">'
                    + '        <thead><tr><th>报警编号</th><th>位置</th><th>时间</th><th>操作</th></tr></thead>'
                    + '        <tbody>' + createAlarmInfo(id, data.alarmInfoList) + '</tbody>'
                    + '    </table>'
                    + '</div>'

                    + '<div class="tab-pane fade" id="mydevice-config">'
                    + '    <table class="table table-bordered table-hover">'
                    + '        <tbody>' + createDeviceConfig(id, type, data.deviceconfig) + '</tbody>'
                    + '    </table>'
                    + '</div>'

                    + '<div class="tab-pane fade" id="mydevice-state">'
                    + '    <table class="table table-hover">'
                    + '        <tbody>' + createDeviceState(id, data.devicestate) + '</tbody>'
                    + '    </table>'
                    + '</div>'

                + '</div>'
            + '</div>';

            openInfoWindow(title, content, marker.getPosition());
        }
    });
}


function openInfoWindow(title, content, position){
    var infoWindow = new AMap.InfoWindow({
        isCustom: true,                                              //使用自定义窗体
        content: createInfoWindow(title, content),
        //content:"map/infoTab.html",
        offset: new AMap.Pixel(16, -45)
    });
    infoWindow.open(map, position);
    map.panTo(position);
}

function createInfoTitle(titletext) {
    return '<span class="infotitle">' + titletext + '</span>';
}

function createTabStr(thead, alarmCheck) {
    var basicActive = '';
    var alarmActive = '';
    if (alarmCheck) {
        alarmActive = ' class="active"';
    } else {
        basicActive = ' class="active"';
    }
    var str =
        '<ul id="myTab" class="nav nav-tabs nav-justified myInfoTab" style="background: #f0f0f0">'
        + '    <li ' + basicActive + '><a href="#mybasic-info" data-toggle="tab">' + thead[0] + '</a></li>'       //基本信息
        + '    <li id="myalarm-infoli"' + alarmActive + '><a href="#myalarm-info" data-toggle="tab">' + thead[1] + '</a></li>'     //报警显示
        + '    <li><a href="#mydevice-config" data-toggle="tab">' + thead[2] + '</a></li>'                     //设备状态
        + '    <li><a href="#mydevice-state" data-toggle="tab">' + thead[3] + '</a></li>'                    //设备配置
        + '</ul>';
    return str;
}

function createBasicInfo(basicInfo) {
    var preDevice = "";
    if(basicInfo.installPreDevice){
        preDevice = basicInfo.installPreDevice + ' > ';
    }
    return '<tr><td>设备编号：' + basicInfo.id + '</td><td>厂商：' + basicInfo.productor + '</td></tr>'
        + '<tr><td>版本：' + basicInfo.productVersion + '</td><td>生产日期：' + basicInfo.productDate + '</td></tr>'
        + '<tr><td>安装人员：' + basicInfo.installer + '</td><td>安装时间：' + basicInfo.installTime + '</td></tr>'
        + '<tr><td colspan="2">安装位置：' + preDevice + basicInfo.installPosition + '</td></tr>';
}

function createAlarmInfo(id, alarmInfoList) {
    if (!alarmInfoList || 0 == alarmInfoList.length) {
        return "暂无报警";
    }
    var str = "", alarmTypeStr = "";
    for (var i in alarmInfoList) {
        var alarminfo  = alarmInfoList[i];
        var id         = alarminfo.id;
        var name       = alarminfo.name;
        var alarmId    = alarminfo.alarmId;
        var alarmTime  = alarminfo.alarmTime;
        var alarmState = alarminfo.alarmState;
        var alarmType  = alarminfo.alarmType;
        var audioUrl   = alarminfo.audioUrl;

        if ("0" == alarmState) {
            var tdid = "alarmtog"+alarmId;
            alarmTypeStr = '<td id="'+tdid+'"><button type="button" class="btn btn-primary btn-xs"'
                + 'deviceId="' + id + '" alarmId="' + alarmId + '" audioUrl="' + audioUrl
                + '" onclick="alarmtoggle(this)">处理</button></td>';
        } else {
            alarmTypeStr = '<td>' + alarmType + '</td>';
        }
        str += '<tr>'
            + '<td>' + alarmId + '</td>'
            + '<td>' + name + '</td>'
            + '<td>' + alarmTime + '</td>'
            + alarmTypeStr
            + '</tr>';
    }
    return str;
}

function createDeviceConfig(id, type, deviceconfig) {
    var devicetogStr = "";
    if(0==type) {                                       //0-中继，1-终端
        devicetogStr = '<button type="button" style="float: right;" class="btn btn-primary col-sm-5" onclick="defendtoggle(this)" deviceId="'+id+'">撤防</button>';
    }
    var shieldDevStr = '<button type="button" style="float: left;" class="btn btn-primary col-sm-5" onclick="shieldtoggle(this)" deviceId="'+id+'">屏蔽设备</button>';

    var configMode = deviceconfig.configMode;
    var modeList   = deviceconfig.modeList;
    var configModeStr  = '<select class="my-select">';
    for(var i in modeList){
        if(configMode == modeList[i]){
            configModeStr += '<option value="' + i + '" selected>'+modeList[i]+'</option>';
        } else {
            configModeStr += '<option value="' + i + '">'+modeList[i]+'</option>';
        }
    }
    configModeStr += "</select>";

    return '<tr><td>当前模式：&nbsp;&nbsp;' + configModeStr + '</td></tr>'
        + '<tr><td>最近报警时间：' + deviceconfig.lastAlarmTime + '</td></tr>'
        + '<tr><td>最近上传时间：' + deviceconfig.lastUploadTime + '</td></tr>'
        + '<tr><td>'+shieldDevStr+devicetogStr+'</td></tr>';

}

function createDeviceState(id, deviceState) {
    return '<tr><td>工作状态：' + deviceState.workState + '</td><td></td></tr>'
        + '<tr><td>网路类型：' + deviceState.netType + '</td><td>网络状态：' + deviceState.netState + '</td></tr>'
        + '<tr><td>设备电量：' + deviceState.power + '</td><td></td></tr>'
        + '<tr><td colspan="2"><button type="button" class="btn btn-primary" onclick="listenertoggle(this)" togState="0" deviceId="'+id+'">启动监听</button>'
        + '<div style="display:inline-block; vertical-align:bottom; margin-left: 20px;">'
        + '<audio id="my-devlistener" controls><span>Your browser does not support this audio format.</span></audio></div></td></tr>';
}

function alarmtoggle(thisitem) {
    var btn = $(thisitem);
    var deviceId = btn.attr("deviceId");
    var alarmId = btn.attr("alarmId");
    var audioUrl = btn.attr("audioUrl");

    var contentstr = getContentstr(deviceId, alarmId, audioUrl);
    openLayer('报警处理', contentstr);                                                          //关闭报警音乐提醒
}

function defendtoggle(thisitem) {
    var btnItem = $(thisitem);
    var deviceId = btnItem.attr("deviceId");

    layer.confirm('确认该操作？', {
        btn: ['确定','取消']                                                //按钮
    }, function(){
        $.ajax({
            type: "POST",
            url: "defendtoggle.json",
            data: {id:deviceId},
            dataType: 'json',
            success: function (data) {
                if (1 != data.action) {
                    return;
                }
                var html;
                var togState = data.togdevice.togState; //0-设备布防，1-设备撤防
                if(0 == togState) {
                    html = "布防";
                    //地图图标变换
                    //btnItem.removeClass('active');
                }else if(1 == togState) {
                    html = "撤防";
                    //btnItem.addClass('active');
                }
                btnItem.text(html);
                addOrCancelDefend(deviceId, togState);      //地图图标变换
                layer.msg(html+'成功！', {icon: 1});
            }
        });
    }, function(){

    });
}

//deviceId 是中继的id
function addOrCancelDefend(deviceId, togState) {
    var device = getPreDevById(deviceId);
    if(!device){
        return;
    }
    var icon, lineColor;
    var type, marker, polyline, circle;
    var childDevlist;

    type = device.type;
    icon = getMarkerIcon_tog(device, type, togState);
    marker = device.marker;
    marker.setIcon(icon);

    if(!device.childDevlist || 0>=device.childDevlist.length){
        return;
    }
    childDevlist = device.childDevlist;
    type = childDevlist[0].type;

    $.each(childDevlist, function(index, childDev){
        marker   = childDev.marker;
        polyline = childDev.polyline;
        circle   = childDev.circle;

        icon      = getMarkerIcon_tog(childDev, type, togState);
        lineColor = getStrokeColor_tog(childDev, type, togState);
        marker.setIcon(icon);
        polyline.setOptions({
            strokeColor: lineColor,
        });
        circle.setOptions({
            strokeColor: lineColor,                 //线颜色
            fillColor: lineColor
        });
    });
}

function getMarkerIcon_tog(device, type, togState) {
    var image, width, height, icon;
    if(0 == togState){
        return getMarkerIcon(device);
    } else if(1 == togState){
        if(0 == type){
            image = resource_mock.IMG_MARKER_TYPE0_WARMING;
            width = height = 24;
        } else if(1 == type) {
            image = resource_mock.IMG_MARKER_TYPE1_WARMING;
            width = height = 36;
        }
        icon = new AMap.Icon({
            size: new AMap.Size(width, height),                   //图标大小
            image: image,
            //imageOffset: new AMap.Pixel(0, 0),                  //图标取图偏移量,可配合size使用
            imageSize: new AMap.Size(width, height)              //图标所用图片大小,会造成无法显示图片？
        });
    }
    return icon;
}

function getStrokeColor_tog(device, type, togState) {
    if(togState==0){
        return getStrokeColor(device.workState, device.alarmState);
    } else if(togState==1) {
        var strokeColorList = [
            strokeColor_mock.COLOR0, strokeColor_mock.COLOR1,
            strokeColor_mock.COLOR2, strokeColor_mock.COLOR3,
            strokeColor_mock.COLOR4, strokeColor_mock.COLOR5,
            strokeColor_mock.COLOR6, strokeColor_mock.COLOR7,
            strokeColor_mock.COLOR8, strokeColor_mock.COLOR9 ];
        var index = 3;
        if (togState && togState == 1) {
            index = 5;
        } else if (togState && togState == 0) {
            index = 3;
        }
        return strokeColorList[index];
    }
}



function shieldtoggle(thisitem) {
    var btnItem = $(thisitem);
    var deviceId = btnItem.attr("deviceId");

    layer.confirm('确认该操作？', {
        btn: ['确定','取消']                                                //按钮
    }, function(){
        $.ajax({
            type: "POST",
            url: "shieldtoggle.json",
            data: {id:deviceId},
            dataType: 'json',
            success: function (data) {
                if (1 != data.action) {
                    return;
                }
                var html;
                var togState = data.togdevice.togState; //0-取消屏蔽，1-屏蔽设备
                if(0 == togState) {
                    html = "取消屏蔽";
                    //btnItem.removeClass('active');
                }else if(1 == togState) {
                    html = "屏蔽设备";
                    //btnItem.addClass('active');
                }
                btnItem.text(html);
                //地图图标变换
                addOrCancelShield(deviceId, togState);
                layer.msg(html+'成功！', {icon: 1});
            }
        });
    }, function(){

    });
}

function addOrCancelShield(deviceId, togState) {
    var device = getDevById(deviceId);
    if(!device){
        return;
    }
    var icon, lineColor;
    var type, marker, polyline, circle;

    type = device.type;
    if(type && type==0) {       //0-中继，1-终端
        icon = getMarkerIcon_tog(device, type, togState);
        marker = device.marker;
        marker.setIcon(icon);

        var childDevlist = device.childDevlist;
        type = childDevlist[0].type;
        $.each(childDevlist, function(index, childDev){
            marker   = childDev.marker;
            polyline = childDev.polyline;
            circle   = childDev.circle;

            icon      = getMarkerIcon_tog(childDev, type, togState);
            lineColor = getStrokeColor_tog(childDev, type, togState);
            marker.setIcon(icon);
            polyline.setOptions({
                strokeColor: lineColor,
            });
            circle.setOptions({
                strokeColor: lineColor,                 //线颜色
                fillColor: lineColor
            });
        });
    } else if(type && type==1) {
        icon      = getMarkerIcon_tog(device, type, togState);
        lineColor = getStrokeColor_tog(device, type, togState);
        marker   = device.marker;
        polyline = device.polyline;
        circle   = device.circle;

        marker.setIcon(icon);
        polyline.setOptions({
            strokeColor: lineColor,
        });
        circle.setOptions({
            strokeColor: lineColor,                 //线颜色
            fillColor: lineColor
        });
    }
}


function listenertoggle(thisitem) {
    var btnItem = $(thisitem);
    var deviceId = btnItem.attr("deviceId");
    var togState = btnItem.attr("togState");        //0-已经关闭监听，1-正在监听
    if("1" == togState){
        $("#my-devlistener")[0].pause();
        btnItem.text("启动监听");
        btnItem.attr("togState", "0");
    } else if("0" == togState) {
        layer.confirm('确认启动监听？', {
            btn: ['确定','取消']                                                    //按钮
        }, function(){
            $.ajax({
                type: "POST",
                url: "listenertoggle.json",
                data: {id:deviceId},
                dataType: 'json',
                success: function (data) {
                    if (1 != data.action) {
                        return;
                    }
                    layer.closeAll();
                    var alarmMedia = $("#my-devlistener");
                    alarmMedia.attr("src",data.toglistener.audioUrl);
                    alarmMedia[0].play();
                    btnItem.text("关闭监听");
                    btnItem.attr("togState", "1");
                }
            });
        }, function(){

        });
    }
}

function getContentstr(deviceId, alarmId, audioUrl) {
    var contentstr =
         '<div style="margin-top:25px">'
        + '    <form class="form-horizontal col-sm-12" role="form">'
        + '         <div class="form-group">'
        + '             <label class="col-sm-2 control-label">播放</label>'
        + '             <div class="col-sm-10" >'
        + '                 <audio controls >'
        + '                     <source src=' + audioUrl + ' type="audio/mpeg">'
        + '                     Your browser does not support this audio format.'
        + '                 </audio>'
        + '             </div>'
        + '        </div>'
        + '        <div class="form-group">'
        + '            <label class="col-sm-2 control-label">处理</label>'
        + '            <div class="col-sm-10">'
        + '                <div class="col-sm-6"><input type="radio" name="optionsRadios" id="optionsRadios0" value="option0">监控报警</div>'
        + '                <div class="col-sm-6"><input type="radio" name="optionsRadios" id="optionsRadios9" value="option9">误报</div>'
        + '            </div>'
        + '        </div>'
        + '        <div class="form-group">'
        + '            <label class="col-sm-2 control-label">其他</label>'
        + '            <div class="col-sm-10">'
        + '                <textarea class="form-control" id="alarmnote" placeholder="其他报警类型" style="width: 90%;"></textarea>'
        + '            </div>'
        + '        </div>'
        + '    </form>'
        + '</div>'
        + '<div style="margin: 0 auto;width:90%;">'
        + '     <div class="col-sm-6">'
        + '         <button type="submit" class="btn btn-primary btn-block" deviceId="' + deviceId + '" alarmId="' + alarmId + '" onclick="checkAlarm(this)">确认</button>'
        + '     </div>'
        + '     <div class="col-sm-6">'
        + '         <button type="submit" class="btn btn-primary btn-block" onclick="checkCancel()">取消</button>'
        + '     </div>'
        + '</div>';
    return contentstr;
}

function checkAlarm(thisitem) {
    var radioVal = $('input:radio[name="optionsRadios"]:checked').val();
    if (!radioVal) {
        alert("请处理报警！");
        return;
    }
    var radioText = getRadioText(radioVal);
    var text = document.getElementById('alarmnote').value;
    if("" != text){
        text = "("+text+")"
    }
//    console.log("radioText:"+radioText+"====text:" + text);

    var btn = $(thisitem);
    var deviceId = btn.attr("deviceId");
    var alarmId = btn.attr("alarmId");
    var device = getDevById(deviceId);
    $.ajax({
        type: "POST",
        url: "checkAlarm.json",
        data: {id:deviceId, alarmId:alarmId},
        dataType: 'json',
        success: function (data) {
            if (1 != data.action) {
                return;
            }
            var checkdevice = data.checkdevice;

            //更新状态
            var alarmState = device.alarmState = checkdevice.alarmState;

            var icon = getMarkerIcon(device);                              //报警图标、颜色
            var strokeColor = getStrokeColor(device.workState,alarmState);
            device.marker.setIcon(icon);
            device.polyline.setOptions({strokeColor: strokeColor});
            device.circle.setOptions({strokeColor: strokeColor});
            device.circle.setOptions({fillColor: strokeColor});

            var ulId = 'marquee-content-items';
            var liId = alarmId;
            deleteliById(ulId, liId);                                      //关闭跑马灯提醒

            stop_bjAlarm();                                                //关闭报警音乐

            layer.closeAll();                                              //关闭layer弹窗

            var tdid = "alarmtog"+alarmId;
            document.getElementById(tdid).innerHTML = '<td >'+radioText+text+'</td>';
        }
    });
}

function checkCancel() {
    layer.closeAll();
}

function getRadioText(radioVal) {
    var str = "";
    switch(radioVal){
        case "option0":
            str = "监控报警";
            break;
        case "option9":
            str = "误报";
            break;
        default:
            str = "其他";
    }
    return str;
}

function openLayer(title, contentstr) {
    layer.open({
        type: 1,
        title: title,
        area: ['450px', '300px'],
        shadeClose: false,               //点击遮罩关闭
        btnAlign: 'c',                   //按钮居中
        content: '\<\div style="margin:10px;">' + contentstr + '\<\/div>',
        closeBtn: 0,
        /*cancel: function(){
            //右上角关闭回调
            return false;                //开启该代码可禁止点击该按钮关闭
         }*/
    });
}


//构建自定义信息窗体
function createInfoWindow(title, content) {
    var info = document.createElement("div");
    info.className = "info";

    //可以通过下面的方式修改自定义窗体的宽高
    //info.style.width = "400px";
    // 定义顶部标题
    var top = document.createElement("div");
    var titleD = document.createElement("div");
    var closeX = document.createElement("img");
    top.className = "info-top";
    titleD.innerHTML = title;
    closeX.src = "http://webapi.amap.com/images/close2.gif";
    closeX.onclick = closeInfoWindow;

    top.appendChild(titleD);
    top.appendChild(closeX);
    info.appendChild(top);

    // 定义中部内容
    var middle = document.createElement("div");
    middle.className = "info-middle";
    middle.style.backgroundColor = 'white';
    middle.innerHTML = content;
    info.appendChild(middle);

    // 定义底部内容
    var bottom = document.createElement("div");
    bottom.className = "info-bottom";
    bottom.style.position = 'relative';
    bottom.style.top = '0px';
    bottom.style.margin = '0 auto';
    var sharp = document.createElement("img");
    sharp.src = "http://webapi.amap.com/images/sharp.png";
    bottom.appendChild(sharp);
    info.appendChild(bottom);
    return info;
}

//关闭信息窗体
function closeInfoWindow() {
    map.clearInfoWindow();
}






